import { Animation, Label, Node, Sprite, SpriteFrame, _decorator, v3 } from 'cc';
import { BaseViewCmpt } from '../../Frame/Script/Base/baseViewCmpt';
import { EventName } from '../../Frame/Script/const/eventName';
import { ViewName } from '../../Frame/Script/const/viewNameConst';
import { E_operationType } from '../../Frame/Script/platform/nativePlatform';
import { ResLoadHelper } from '../../Frame/Script/resLoadHelper';
import { App } from '../app';
import { NetInfo } from '../core/NetInfo';
import { GameModeCmd, LiveRoomCmd, PlayerCmd, SeatCmd, SubModeCmd } from '../network/net_proto/protocols/commonRoom';
import { MsgJoinOrLeaveLivingRoom } from '../network/net_proto/protocols/game/MsgJoinOrLeaveLivingRoom';
import { MsgJoinOrLeaveSeat } from '../network/net_proto/protocols/game/MsgJoinOrLeaveSeat';
import { MsgReadyOrNot } from '../network/net_proto/protocols/game/MsgReadyOrNot';
import { MsgSelectModel } from '../network/net_proto/protocols/game/MsgSelectModel';
import { MsgStartGame } from '../network/net_proto/protocols/game/MsgStartGame';


const { ccclass, property } = _decorator;
const modelSeatLocation = {
	1: [-210, -70, 70, 210],
	2: [-230, -100, 100, 230]
}

@ccclass('HomeViewManager')
export class HomeViewManager extends BaseViewCmpt {

	/** 座位列表 */
	private seatList: Array<Node> = [];
	/** 游戏模式 */
	private game_modal: Node = null;
	/** 游戏类型 */
	private game_group1: Node = null;
	private game_group2: Node = null;
	/** 中间按钮 */
	private middleBtns: Node = null;
	/** 加入游戏按钮动画 */
	private btnJoinAnima: Animation = null;
	/** 排行榜按钮节点 */
	private btnRank: Node = null;

	protected onLoad(): void {
		super.onLoad();
		for (let i = 1; i <= 4; i++) {
			let seat = this.viewList.get("content/panel/bottomUI/seat" + i);
			this.seatList.push(seat);
		}
		this.game_modal = this.viewList.get("content/panel/modelToggleGroup");
		this.game_group1 = this.viewList.get("content/panel/typePar/group1");
		this.game_group2 = this.viewList.get("content/panel/typePar/group2");
		this.middleBtns = this.viewList.get("content/panel/middleBtns");
		this.btnRank = this.viewList.get("content/panel/btnRank");
		/** 目前排行榜未实现，暂时隐藏 */
		this.btnRank.active = false;
		this.btnJoinAnima = this.viewList.get("content/panel/middleBtns/btnJoin/join_anima").getComponent(Animation);

		App.event.on(EventName.Game.JOIN_OR_LEAVE_ROOM_TO_VIEW, this.onJoinOrLeaveRoom, this);
		App.event.on(EventName.Game.JOIN_OR_LEAVE_SEAT_TO_VIEW, this.onJoinOrLeaveSeat, this);
		App.event.on(EventName.Game.READY_OR_NOT_TO_VIEW, this.onReadyOrNot, this);
		App.event.on(EventName.Game.SELECT_MODEL_TO_VIEW, this.onSelectModel, this);
		App.event.on(EventName.Game.START_GAME_TO_VIEW, this.onStartGame, this);
	}

	start() {
		this.updateRoomShow(this.extraData[0]);
	}

	protected onDestroy(): void {
		App.event.off(EventName.Game.JOIN_OR_LEAVE_ROOM_TO_VIEW, this);
		App.event.off(EventName.Game.JOIN_OR_LEAVE_SEAT_TO_VIEW, this);
		App.event.off(EventName.Game.READY_OR_NOT_TO_VIEW, this);
		App.event.off(EventName.Game.SELECT_MODEL_TO_VIEW, this);
		App.event.off(EventName.Game.START_GAME_TO_VIEW, this);
	}

	/** 监听玩家加入和离开房间 */
	private onJoinOrLeaveRoom(data: MsgJoinOrLeaveLivingRoom) {
		console.log("MsgJoinOrLeaveLivingRoom=>", data);
		if (!data.isJoin) {
			this.updateAllSeatContent(App.gameData.getGameSeats());
		}
	}

	/** 监听玩家加入和离开座位 */
	private onJoinOrLeaveSeat(data: MsgJoinOrLeaveSeat) {
		this.updateOneSeatContent(data.seatId, data.joinUser);
		if (data.isJoin) {
			if (data.uid === NetInfo.uid) {
				let middleBtnType = data.seatId === 1 ? 1 : 2;
				this.updateMiddleBtns(middleBtnType);
			}
		} else {
			if (data.uid === NetInfo.uid) {
				this.updateMiddleBtns(0);
			}
		}
	}

	/** 监听玩家准备 */
	private onReadyOrNot(data: MsgReadyOrNot) {
		let index = data.seatId - 1;
		let seatNode = this.seatList[index];
		seatNode.getChildByName("img_ready").active = data.isReady;
	}

	/** 监听模式切换 */
	private onSelectModel(data: MsgSelectModel) {
		this.updateModelContent(data.model, data.subModel);
		this.setSeatPos(data.model);
		let seats = App.gameData.getGameSeats();
		for (let i = 0; i < 4; i++) {
			let seat_data = seats[i];
			let seat_id = seat_data.id;
			if (seat_id > 1 && seat_data.user) {
				let seatNode = this.seatList[i];
				seatNode.getChildByName("img_ready").active = false;
				seat_data.user.isReady = false;
				if (seat_data.user.uid === NetInfo.uid) {
					this.updateMiddleBtns(2);
				}
			}
		}
	}

	/** 监听游戏开始 */
	private onStartGame(data: MsgStartGame) {
		let model = App.gameData.getModelData();
		this.onClick_closeBtn();
		if (model === GameModeCmd.合作模式) {
			App.view.openView(ViewName.Single.eModel1View);
		} else if (model === GameModeCmd.对抗模式) {
			App.view.openView(ViewName.Single.eVsView);
		} else {
			console.error("game model err:", model);
		}
	}

	/** 游客进入房间后，更新房间显示 */
	private updateRoomShow(roomData: LiveRoomCmd) {
		let model: number = roomData ? roomData.model : App.gameData.getModelData();
		let type: number = roomData ? roomData.subModel : App.gameData.getTypeData();
		let seats = roomData ? roomData.seats : App.gameData.getGameSeats();
		let seatId = App.user.seatId;
		App.gameData.setModelData(model);
		App.gameData.setTypeData(type);
		App.gameData.setGameSeats(seats);
		this.setSeatPos(model);
		this.updateModelContent(model, type);
		this.updateAllSeatContent(seats);
		if (seatId === 0) {
			this.updateMiddleBtns(0);
		} else {
			if (seatId === 1) {
				this.updateMiddleBtns(1);
			} else {
				if (seats[seatId - 1].user) {
					let isReady = seats[seatId - 1].user.isReady;
					let value = isReady ? 3 : 2;
					this.updateMiddleBtns(value);
				}
			}
		}
	}

	/** 处理点击座位 */
	private async dealWithTakeSeat(seatNum: number) {
		// console.log("onClick_seat" + seatNum);
		let seats = App.gameData.getGameSeats();
		let seat_data = seats[seatNum - 1];
		if (seat_data && seat_data.user && NetInfo.uid !== seat_data.user.uid) {
			App.view.showMsgTips("查看座位上的玩家信息");
			console.log("查看座位上的玩家信息，调用原生端的方法");
			return;
		}
		if (App.user.seatId === 0) {
			await App.ws.callApi("game/JoinGame", {
				session: NetInfo.session,
				seatId: seatNum,
			})
		} else if (App.user.seatId === seatNum) {
			App.view.openView(ViewName.Single.eLeavaView);
		} else {
			App.view.showMsgTips("你已经在麦上，不能再次上麦");
			return;
		}
	}

	/** 根据模式设置座位的坐标 */
	private setSeatPos(model: number) {
		let posList = modelSeatLocation[model];
		this.seatList.forEach((e, index) => {
			e.setPosition(v3(posList[index], 0, 0));
		})
		this.viewList.get("content/panel/bottomUI/vs").active = model === 2;
	}

	/** 更新整体模式和类型的显示*/
	private updateModelContent(model: number, type: number) {
		if (model === 1) {
			this.game_modal.children[0].children[0].active = true;
			this.game_modal.children[0].children[1].active = true;
			this.game_modal.children[1].children[0].active = false;
			this.game_modal.children[1].children[1].active = false;
			this.game_group1.active = true;
			this.game_group2.active = false;
			this.game_group1.children[0].getChildByName("Checkmark").active = type === 1;
			this.game_group1.children[1].getChildByName("Checkmark").active = type === 2;
			// this.btnRank.active = true;
		} else if (model === 2) {
			this.game_modal.children[0].children[0].active = false;
			this.game_modal.children[0].children[1].active = false;
			this.game_modal.children[1].children[0].active = true;
			this.game_modal.children[1].children[1].active = true;
			this.game_group1.active = false;
			this.game_group2.active = true;
			this.game_group2.children[0].getChildByName("Checkmark").active = type === 3;
			this.game_group2.children[1].getChildByName("Checkmark").active = type === 4;
			// this.btnRank.active = false;
		}
	}

	/** 更新所有座位的显示 */
	private updateAllSeatContent(list: Array<SeatCmd>) {
		for (let i = 0; i < list.length; i++) {
			let data = list[i];
			let id = data.id;
			let user_data = data.user ? data.user : null;
			this.updateOneSeatContent(id, user_data);
		}
	}

	/** 更新单个座位的显示 */
	private updateOneSeatContent(seatId: number, userData: PlayerCmd) {
		let seats = App.gameData.getGameSeats();
		seats[seatId - 1].user = userData ? userData : null;
		let name = userData ? userData.name : App.gameData.LanguageData[13];
		let icon = userData ? userData.icon : "";
		let isReady = userData ? userData.isReady : false;
		let target = this.seatList[seatId - 1];
		let name_label = target.getChildByName("Label").getComponent(Label);
		let head_spr = target.getChildByName("mask").getChildByName("head").getComponent(Sprite);
		name_label.string = name;
		target.getChildByName("img_ready").active = seatId === 1 ? false : isReady;
		if (icon) {
			head_spr.node.active = true;
			ResLoadHelper.loadAssetAsync(icon, SpriteFrame, (frame: SpriteFrame) => {
				head_spr.spriteFrame = frame;
			}, true)
		} else {
			head_spr.node.active = false;
		}
	}

	/**
	* 更新中间按钮的显示
	* 0：Join  加入游戏
	* 1: Start 开始游戏
	* 2: Reserve 准备
	* 3: CancelReserve 取消准备
	*/
	private updateMiddleBtns(num: number) {
		if (num === 0) {
			this.btnJoinAnima.play();
		} else {
			this.btnJoinAnima.stop();
		}
		this.middleBtns.children.forEach((e, index) => {
			e.active = index === num;
		})
	}

	//******************************模式选择****************************************** */
	private async onModelCheck(event) {
		if (this.checkSeatId("model")) return;
		let model = Number(event.target.name.slice(-1));
		let modelCmd: GameModeCmd = null;
		let subModelCmd: SubModeCmd = null;
		if (model === 1) {
			modelCmd = GameModeCmd.合作模式;
			subModelCmd = SubModeCmd.简单;
		} else if (model === 2) {
			modelCmd = GameModeCmd.对抗模式;
			subModelCmd = SubModeCmd.经典;
		}
		await App.ws.callApi("game/SelectModel", {
			session: NetInfo.session,
			model: modelCmd,
			subModel: subModelCmd
		})
	}

	private async onTypeGroup1Check(event) {
		if (this.checkSeatId("type")) return;
		let type = Number(event.target.name.slice(-1));
		let modelCmd: GameModeCmd = GameModeCmd.合作模式;
		let subModelCmd: SubModeCmd = null;
		if (type === 1) {
			subModelCmd = SubModeCmd.简单;
		} else if (type === 2) {
			subModelCmd = SubModeCmd.困难;
		}
		await App.ws.callApi("game/SelectModel", {
			session: NetInfo.session,
			model: modelCmd,
			subModel: subModelCmd
		})
	}

	private async onTypeGroup2Check(event) {
		if (this.checkSeatId("type")) return;
		let type = Number(event.target.name.slice(-1));
		let modelCmd: GameModeCmd = GameModeCmd.对抗模式;
		let subModelCmd: SubModeCmd = null;
		/** 技能对战功能没有 */
		if (type === 4) {
			App.view.showMsgTips(App.gameData.LanguageData[81]);
			return;
		}
		if (type === 3) {
			subModelCmd = SubModeCmd.经典;
		}
		await App.ws.callApi("game/SelectModel", {
			session: NetInfo.session,
			model: modelCmd,
			subModel: subModelCmd
		})
	}

	private checkSeatId(str: string): boolean {
		if (App.user.seatId === 1) {
			return false;
		} else {
			switch (str) {
				case "model":
					App.view.showMsgTips(App.gameData.LanguageData[21]);
					break;
				case "type":
					App.view.showMsgTips(App.gameData.LanguageData[6]);
					break
				default:
					break;
			}
			return true;
		}

		/** 测试使用 */
		// return false
	}

	//*******************************按钮回调***************************************************** */
	/** 排行榜按钮回调 */
	onClick_btnRank() {
		App.view.openView(ViewName.Single.eRankView);
	}

	/** 帮助按钮回调 */
	onClick_btnHelp() {
		App.view.openView(ViewName.Single.eRuleView);
	}

	/** 加入游戏按钮回调 */
	async onClick_btnJoin() {
		let seats = App.gameData.getGameSeats();
		let count = 0
		for (let data of seats) {
			if (data.user) {
				count += 1;
				if (count === 4) {
					App.view.showMsgTips(App.gameData.LanguageData[1]);
					return;
				}
			} else {
				break;
			}
		}
		/** 加入游戏：向服务器端发送请求，获取空位的座位号 */
		await App.ws.callApi("game/JoinGame", { session: NetInfo.session })
	}

	/** 开始游戏按钮回调 */
	async onClick_btnStart() {
		let msg = await App.ws.callApi("game/StartGame", { session: NetInfo.session });
		console.log("onClick_btnStart", msg);
		if (!msg.isSucc) {
			if (msg.err.message === "人数不足") {
				App.view.showMsgTips(App.gameData.LanguageData[22]);
			} else if (msg.err.message === "已准备人数不足") {
				App.view.showMsgTips(App.gameData.LanguageData[2]);
			} else if (msg.err.message === "还有玩家未准备") {
				App.view.showMsgTips(App.gameData.LanguageData[2]);
			}
		}
	}

	/** 准备按钮回调 */
	async onClick_btnReserve() {
		if (App.user.seatId <= 0) return;
		/** 向服务器发送 准备  请求 */
		let msg = await App.ws.callApi("game/ReadyOrNot", {
			isReady: true,
			session: NetInfo.session
		})
		if (msg.isSucc) this.updateMiddleBtns(3);
	}

	/** 取消准备按钮回调 */
	async onClick_btnCancelReserve() {
		if (App.user.seatId <= 0) return;
		/** 向服务器发送 取消准备  请求 */
		let msg = await App.ws.callApi("game/ReadyOrNot", {
			isReady: false,
			session: NetInfo.session
		})
		if (msg.isSucc) this.updateMiddleBtns(2);
	}

	//*************************座位回调******************************** */
	onClick_seat1() {
		// this.dealWithTakeSeat(1);
		App.platform.jsCallJava(E_operationType.upMic)
		App.view.showMsgTips("点击一号位上麦")
	}

	onClick_seat2() {
		App.view.showMsgTips("点击二号位")
		// this.dealWithTakeSeat(2);
	}

	onClick_seat3() {
		App.view.showMsgTips("点击三号位")
		// this.dealWithTakeSeat(3);
	}

	onClick_seat4() {
		App.platform.jsCallJava(E_operationType.downMic)
		App.view.showMsgTips("点击四号位下麦")
		// this.dealWithTakeSeat(4);
	}
}


